<?php

namespace app\advertisement\logic;

use app\advertisement\model\Advaccount as AdvaccountModel;
use think\facade\Db;
use app\data\util\HttpUtil;
use think\facade\Config;
use ba\Exception;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;

class ApiAdvaccountLogic
{
    protected $app_id = "";
    protected $secret = "";
    protected $access_token = "";
    protected $model = null;

    public function __construct()
    {
        $this->model = new AdvaccountModel();
        $this->app_id = '7308904668262825985';
        $this->secret = '14c2acb1dfefa9ed5ce2886a09f909e56f0a81b3';
        $this->access_token = '34b8c8d339449f55857ba6ffcac996adb10a9db4';
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 广告账户列表
     * @author zhangheng
     */
    public function getApiAdvaccountsList($params = [])
    {  
        $app_id = $this->app_id;
        $secret = $this->secret;
        $url = "https://business-api.tiktok.com/open_api/v1.3/oauth2/advertiser/get/?app_id=".$app_id."&secret=".$secret;
        $return = HttpUtil::ApiAdvaccountsGetUrl($url, $this->access_token);
        $return = json_decode($return, true);
        try {
            Db::startTrans(); // 开启事务
            if(isset($return['data']['list']) && !empty($return['data']['list'])){
                foreach ($return['data']['list'] as $adv) {
                    //更新广告账户
                    $advaccount = Db::name('advaccount')->where('advertiser_id', $adv['advertiser_id'])->find();
                    $data = [
                        'adv' => "Tiktok",
                        'advertiser_id' => $adv['advertiser_id'],
                        'advertiser_name' => $adv['advertiser_name'],
                    ];
                    if(empty($advaccount)){
                        Db::name('advaccount')->insert($data);
                    } else {
                        Db::name('advaccount')->where('id', $advaccount['id'])->update($data);
                    }
                }
            }
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '操作成功', ''));
        } catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author zhangheng
     */
    public function IntegratedList($params)
    {
        switch ($params['type']) {
            case '1'://更新之前的广告花费
                $returns = $this->IntegratedBefore($params['page'],$params['advertiser_id']);
                return json(DefaultResponse(200, true, '操作成功', $returns));
                break;
            case '2'://实时更新的广告花费
                $this->IntegratedRealtime();
                break;
            default:
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 更新之前的广告花费
     * @author zhangheng
     */
    public function IntegratedBefore($page,$advertiser_id){ 
        $advplat = Db::name('advaccount')  
            ->where('updatetime_automatic', '>', '2023-10-01')
            ->where('advertiser_id', $advertiser_id)
            ->order('integrated_time asc')
            ->find();
        if (!empty($advplat)) {
            $update = [];
                
            if (!empty($advplat['updatetime_automatic']) && strtotime($advplat['updatetime_automatic']) > 1696089600) {//更新到2023-10-01 00:00:00
                //以广告账户维度----数据跑完了
                // $this->integrated_get($advplat, $advplat['updatetime_automatic']);
                //以广告系列维度
                $update['updatetime_automatic'] = date('Y-m-01', strtotime($advplat['updatetime_automatic']));
                // https://newtiktok.chandao.icu/advertisement/ApiAdvaccount/IntegratedList?type=1&page=2
                $returns = $this->integratedCampaign_get_month($advplat, $update['updatetime_automatic'],$page);
                return $returns;
                // $update['updatetime_automatic'] = date('Y-m-d', strtotime($update['updatetime_automatic']) - 1);
            }
            
            // $update['integrated_time'] = time();
            // Db::name('advaccount')
            //     ->where('id', $advplat['id'])
            //     ->update($update);
        }
        return true;
    }

    /**
    * mq队列回调
    * @param array params
    */
    public function tiktok_campaign_list($item)
    {
        $stat_time_day = $item['dimensions']['stat_time_day'];
        $campaign_id = $item['metrics']['campaign_id'];
        $ad_id = $item['dimensions']['ad_id'];

        $advertisingData = [
            'advertiser_id' => $item['advertiser_id'],
            'stat_time_day' => $stat_time_day,
            'campaign_id' => $campaign_id,
            'stat_time' => strtotime($stat_time_day),
            'ad_id' => $ad_id,
            'spend' => $item['metrics']['spend'],
            'conversion' => $item['metrics']['conversion'],
            'onsite_shopping_roas' => $item['metrics']['onsite_shopping_roas'],
            'campaign_name' => $item['metrics']['campaign_name'],
            'total_onsite_shopping_value' => $item['metrics']['total_onsite_shopping_value'],
            'ad_name' => $item['metrics']['ad_name']
        ];
        //只能改API的数据
        $existingAdvertising = Db::name('advertising_campaign')
            ->where('stat_time_day', $stat_time_day)
            ->where('ad_id', $ad_id)
            ->find();
        if (empty($existingAdvertising)) {
            Db::name('advertising_campaign')->insert($advertisingData);
        } else {
            Db::name('advertising_campaign')
                ->where('stat_time_day', $stat_time_day)
                ->where('ad_id', $ad_id)
                ->update($advertisingData);
        }

        return $advertisingData;
    }
    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 实时更新的广告花费
     * @author zhangheng
     */
    public function IntegratedRealtime()
    {
        $advplat = Db::name('advaccount')
            ->order('integrated_time_new asc')
            ->find();

        if (!empty($advplat)) {
                $updatetime_automatic = date('Y-m-d', time());
                //以广告账户维度
                $this->integrated_get($advplat, $updatetime_automatic);
                //以广告系列维度
                $this->integratedCampaign_get($advplat, $updatetime_automatic,2);

                $update = [
                    'integrated_time_new' => time()
                ];

                Db::name('advaccount')
                    ->where('id', $advplat['id'])
                    ->update($update);
        }
        return true;
    }

    /**
    * @param array params
    * 每天转点之后更新所有广告账户当天的数据
    */
    public function tiktok_integrated_list($item)
    {
        $stat_time_day = $item['dimensions']['stat_time_day'];
        $advertiser_id = $item['dimensions']['advertiser_id'];

        $advertisingData = [
            'stat_time_day' => $stat_time_day,
            'advertiser_id' => $advertiser_id,
            'spend' => $item['metrics']['spend'],
            'type' => 0,
            'impressions' => $item['metrics']['impressions']
        ];
        //只能改API的数据
        $existingAdvertising = Db::name('advertising')
            ->where('stat_time_day', $stat_time_day)
            ->where('advertiser_id', $advertiser_id)
            ->where('type', 0)
            ->find();
        if (empty($existingAdvertising)) {
            Db::name('advertising')->insert($advertisingData);
        } else {
            Db::name('advertising')
                ->where('stat_time_day', $stat_time_day)
                ->where('advertiser_id', $advertiser_id)
                ->where('type', 0)
                ->update($advertisingData);
        }
    }
    /**
    * @param array params
    * 以广告账户维度
    */
    public function integrated_get($v,$date_end)
    {
        $date_start = date('Y-m-d', strtotime($date_end) - 2 * 24 * 3600);
        $advertiser_id = $v['advertiser_id'];
        $dimensions = ['advertiser_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $url = "https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date_start."&end_date=".$date_end;
        $return = HttpUtil::ApiAdvaccountsGetUrl($url, $this->access_token);
        $return = json_decode($return, true);

        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {
                //队列
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_TIKTOK_INTEGRATED_LIST_QUEUE,
                    $item,
                    false
                );
            }
        }
        return true;
    }

    /**
    * @param array params
    * 以广告系列维度
    */
    public function integratedCampaign_get($v,$date_end,$type)
    {
        //更新之前的
        if($type == 1){
            $date_start = date('Y-m-d', strtotime($date_end) - 2 * 24 * 3600);
        }else{
            $date_start = date('Y-m-d', strtotime($date_end) - 2 * 24 * 3600);
        }
        
        // $date_start = "2024-03-01";
        // $date_end = "2024-03-31";
        // dump($date_start);die;
        $advertiser_id = $v['advertiser_id'];
        $dimensions = ['ad_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $metrics = [
            "campaign_id",
            "campaign_name",
            "spend",
            "ad_name",
            "onsite_shopping_roas",
            "total_onsite_shopping_value",
            "conversion"
        ];
        
        $filtering[0]["field_name"] = "ad_status";
        $filtering[0]["filter_type"] = "IN";
        $filterValue = ["STATUS_ALL"];
        $encodedFilterValue = json_encode($filterValue); 
        $filtering[0]["filter_value"] = $encodedFilterValue;
        $filtering = json_encode($filtering, true);
        
        $metrics = json_encode($metrics, true);
        $url = "https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_AD&report_type=BASIC&dimensions=".$dimensions."&metrics=".$metrics."&filtering=".$filtering."&page_size=1000&start_date=".$date_start."&end_date=".$date_end;
        $return = HttpUtil::ApiAdvaccountsGetUrl($url, $this->access_token);
        $return = json_decode($return, true);
        // dump($return);die;
        $items = [];
        $spend = 0;
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {    
                $item['advertiser_id'] = $advertiser_id;
                $item = $this->tiktok_campaign_list($item);
                // if($item['spend'] > 0.001){
                    $items[] = $item;  
                    $spend += $item['spend'];  
                // }
        
                //队列
                // MqTaskPushLogic::mq_task_push(
                //     '',
                //     MqQueueName::QUEUE_TIKTOK_CAMPAIGN_LIST_QUEUE,
                //     $item,
                //     false
                // );
            }
            // dump($items);die;
            if(!empty($items)){
                Db::name('advertising_campaign')
                    ->where('stat_time',">=", strtotime($date_start))
                    ->where('stat_time',"<=", strtotime($date_end))
                    ->where('advertiser_id', $advertiser_id)
                    ->delete();
                Db::name('advertising_campaign')->insertAll($items);
            }
        }
        return true;
    }

    public function CalculateDailyAdvExpenses($params)
    {
        for ($i = 0; $i <= 2; $i++) {  
            $this->CalculateDailyAdvExpenses2($i);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }  
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author zhangheng
     */
    public function CalculateDailyAdvExpenses2($params)
    {
        //转点拉取
        $time = strtotime(date('Y-m-d',time() - 16 * 3600 - 24 * 3600 * $params));
        $list = Db::name('advertising_campaign')
            ->where("stat_time","<=",1711814400)
            ->where("stat_time",">=",1709222400)
            // ->where("spend", '>=', 0.001)
            ->select()
            ->toarray();
        $spendTotal = [];
        //配置
        
        $config  = Config::get('Logisticskey.' . 'PerformanceRulesForAdvertising');
        //重组
        foreach ($list as $item) {
            foreach ($config as $campaign) {
                if (strpos(strtolower($item['campaign_name']), $campaign[2]) !== false) {
                    if($campaign[2] == "myj"){
                        $campaign[2] = "mengyujiao";
                    }
                    if($campaign[2] == "zhangyememg"){
                        $campaign[2] = "zhangyemeng";
                    }
                    if($campaign[2] == "spk"){
                        $campaign[2] = "qiujingwen";
                    }
                    if($campaign[2] == "mengyujiaao"){
                        $campaign[2] = "mengyujiao";
                    }
                    if($campaign[2] == "chengben"){
                        $campaign[2] = "qiujingwen";
                    }
                    if($campaign[2] == "dailaing"){
                        $campaign[2] = "dailiang";
                    }
                    $campaignKey = $campaign[2];
                    $campaignKeyCompany = $campaign[1];
                    $campaignKeyName = $campaign[0];
                    break;
                }
            }
            if (isset($campaignKey) && isset($campaignKeyCompany) && isset($campaignKeyName)) {
                if (!isset($spendTotal[$campaignKey])) {
                    //统计
                    $spendTotal[$campaignKey]['spend'] = 0;
                    $spendTotal[$campaignKey]['conversion'] = 0;
                    $spendTotal[$campaignKey]['total_onsite_shopping_value'] = 0;
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = 0;
                    $spendTotal[$campaignKey]['company'] = $campaignKeyCompany;
                    $spendTotal[$campaignKey]['name'] = $campaignKeyName;
                }
                $spendTotal[$campaignKey]['spend'] += $item['spend'];
                $spendTotal[$campaignKey]['conversion'] += $item['conversion'];
                $spendTotal[$campaignKey]['total_onsite_shopping_value'] += $item['total_onsite_shopping_value'];
                if(!empty($spendTotal[$campaignKey]['total_onsite_shopping_value']) && !empty($spendTotal[$campaignKey]['spend'])){
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = number_format($spendTotal[$campaignKey]['total_onsite_shopping_value'] / $spendTotal[$campaignKey]['spend'], 2, '.', '');
                }
                unset($campaignKey);
                unset($campaignKeyCompany);
                unset($campaignKeyName);
            }
        }
        // dump($spendTotal);die;
        if(!empty($spendTotal)){
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'stat_time_day' => $time,
                    'spend' => $v['spend'],
                    'conversion' => $v['conversion'],
                    'total_onsite_shopping_value' => $v['total_onsite_shopping_value'],
                    'onsite_shopping_roas' => $v['onsite_shopping_roas'],
                    'company' => $v['company'],
                    'name' => $v['name'],
                ];
                //只能改API的数据
                $existingReport = Db::name('advertising_report')
                    ->where('stat_time_day', $time)
                    ->where('name', $v['name'])
                    ->find();
                if (empty($existingReport)) {
                    Db::name('advertising_report')->insert($advertisingData);
                } else {
                    Db::name('advertising_report')
                        ->where('stat_time_day', $time)
                        ->where('name', $v['name'])
                        ->update($advertisingData);
                }
            }
        }
        return true;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author zhangheng
     * 临时任务
     */
    public function TemporaryTasks($params)
    {
        //方法1-更新订单退款情况
        $orders = Db::name('order')
            ->where('tasktime',0)
            ->select()
            ->toarray();
        foreach ($orders as $order) {
            // $this->temporary_tasks($order);
            // 队列
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_Temporary_Tasks_QUEUE,
                $order,
                false
            );
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * @param array params
    * 临时任务
    */
    public function temporary_tasks($order)
    { 
        $data = array();
        $order_ids = array();
        $order_ids[] = $order['order_id'];
        $data['order_ids'] = $order_ids;
        $order_ids = json_encode($order_ids,true);

        $shop      = Db::name('shops')->where("id", $order['shop_id'])->find();
        $tik_info  = Config::get('Logisticskey.' . 'TIKTOK');
        $baseUrl   = $tik_info['basic_url'];
        $path      = $tik_info['cancellations_search_path'];
        $sign      = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'page_size50shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '{"order_ids":'.$order_ids.'}' . $shop['app_secret'];
        $sign      = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url       = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&page_size=50&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $return    = HttpUtil::tikPostUrl($url,$data, $shop['access_token']);
        if (isset($return['data']['cancellations']) && !empty($return['data']['cancellations'])){
            $cancellations = $return['data']['cancellations'];
            foreach ($cancellations as $cancellation) {
                $arr = array();
                $arr['order_id'] = $cancellation['order_id'];
                $arr['shop_id'] = $shop['id'];
                $arr['cancel_reason'] = $cancellation['cancel_reason'];
                $arr['cancel_reason_text'] = $cancellation['cancel_reason_text'];
                $arr['cancel_status'] = $cancellation['cancel_status'];
                $arr['cancel_type'] = $cancellation['cancel_type'];
                $arr['create_time'] = $cancellation['create_time'];
                $arr['role'] = $cancellation['role'];
    
                if (isset($cancellation['cancel_line_items']) && !empty($cancellation['cancel_line_items'])) {
                    $arr['cancel_line_items'] = json_encode($cancellation['cancel_line_items'], true);
                }
                if (isset($cancellation['refund_amount']) && !empty($cancellation['refund_amount'])) {
                    $amountKeys = ['currency', 'refund_shipping_fee', 'refund_subtotal', 'refund_tax', 'refund_total', 'retail_delivery_fee'];
                
                    foreach ($amountKeys as $key) {
                        $arr[$key] = $cancellation['refund_amount'][$key] ?? '';
                    }
                }
    
                $orderrefund = Db::name('order_refund')->where(['order_id' => $cancellation['order_id']])->find();
                if(!empty($orderrefund)){
                    Db::name('order_refund')->where('id',$orderrefund['id'])->update($arr);
                }else{
                    Db::name('order_refund')->insert($arr);
                }
            }
        }
        Db::name('order')->where('order_id',$order['order_id']) ->update([
            'tasktime' => time(),
        ]);
        return true;
    }

    public function ExpertVideo($params)
    {
        for ($i = 0; $i <= 2; $i++) {  
            $this->ExpertVideos($i);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }  
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author zhangheng
     */
    public function ExpertVideos($params)
    {
        //转点拉取
        $time = strtotime(date('Y-m-d',time() - 16 * 3600 - 24 * 3600 * $params));
        $list = Db::name('advertising_campaign')
            ->where("stat_time",$time)
            // ->where("spend", '>=', 0.001)
            ->select()
            ->toarray();
        $spendTotal = [];
        //配置
        
        $config  = Config::get('Logisticskey.' . 'ExpertVideo');
        //重组
        foreach ($list as $item) {
            foreach ($config as $campaign) {
                if (strpos(strtolower($item['ad_name']), $campaign[1]) !== false) {
                    $campaignKey = $campaign[1];
                    $campaignKeyName = $campaign[0];
                    break;
                }
            }
            if (isset($campaignKey) && isset($campaignKeyName)) {
                if (!isset($spendTotal[$campaignKey])) {
                    //统计
                    $spendTotal[$campaignKey]['spend'] = 0;
                    $spendTotal[$campaignKey]['conversion'] = 0;
                    $spendTotal[$campaignKey]['total_onsite_shopping_value'] = 0;
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = 0;
                    $spendTotal[$campaignKey]['name'] = $campaignKeyName;
                }
                $spendTotal[$campaignKey]['spend'] += $item['spend'];
                $spendTotal[$campaignKey]['conversion'] += $item['conversion'];
                $spendTotal[$campaignKey]['total_onsite_shopping_value'] += $item['total_onsite_shopping_value'];
                if(!empty($spendTotal[$campaignKey]['total_onsite_shopping_value']) && !empty($spendTotal[$campaignKey]['spend'])){
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = number_format($spendTotal[$campaignKey]['total_onsite_shopping_value'] / $spendTotal[$campaignKey]['spend'], 2, '.', '');
                }
                unset($campaignKey);
                unset($campaignKeyName);
            }
        }
        if(!empty($spendTotal)){
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'stat_time_day' => $time,
                    'spend' => $v['spend'],
                    'conversion' => $v['conversion'],
                    'total_onsite_shopping_value' => $v['total_onsite_shopping_value'],
                    'onsite_shopping_roas' => $v['onsite_shopping_roas'],
                    'name' => $v['name'],
                ];
                //只能改API的数据
                $existingReport = Db::name('advertising_expertvideo')
                    ->where('stat_time_day', $time)
                    ->where('name', $v['name'])
                    ->find();
                if (empty($existingReport)) {
                    Db::name('advertising_expertvideo')->insert($advertisingData);
                } else {
                    Db::name('advertising_expertvideo')
                        ->where('stat_time_day', $time)
                        ->where('name', $v['name'])
                        ->update($advertisingData);
                }
            }
        }
        return true;
    }

    public function EditingVideo($params)
    {
        for ($i = 0; $i <= 2; $i++) {  
            $this->EditingVideos($i);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }  
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author zhangheng
     */
    public function EditingVideos($params)
    {
        //转点拉取
        $time = strtotime(date('Y-m-d',time() - 16 * 3600 - 24 * 3600 * $params));
        $list = Db::name('advertising_campaign')
            ->where("stat_time",$time)
            // ->where("spend", '>=', 0.001)
            ->select()
            ->toarray();
        $spendTotal = [];
        //配置
        
        $config  = Config::get('Logisticskey.' . 'EditingVideos');
        //重组
        foreach ($list as $item) {
            foreach ($config as $campaign) {
                if (strpos(strtolower($item['ad_name']), $campaign[1]) !== false) {
                    $campaignKey = $campaign[1];
                    $campaignKeyName = $campaign[0];
                    break;
                }
            }
            if (isset($campaignKey) && isset($campaignKeyName)) {
                if (!isset($spendTotal[$campaignKey])) {
                    //统计
                    $spendTotal[$campaignKey]['spend'] = 0;
                    $spendTotal[$campaignKey]['conversion'] = 0;
                    $spendTotal[$campaignKey]['total_onsite_shopping_value'] = 0;
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = 0;
                    $spendTotal[$campaignKey]['name'] = $campaignKeyName;
                }
                $spendTotal[$campaignKey]['spend'] += $item['spend'];
                $spendTotal[$campaignKey]['conversion'] += $item['conversion'];
                $spendTotal[$campaignKey]['total_onsite_shopping_value'] += $item['total_onsite_shopping_value'];
                if(!empty($spendTotal[$campaignKey]['total_onsite_shopping_value']) && !empty($spendTotal[$campaignKey]['spend'])){
                    $spendTotal[$campaignKey]['onsite_shopping_roas'] = number_format($spendTotal[$campaignKey]['total_onsite_shopping_value'] / $spendTotal[$campaignKey]['spend'], 2, '.', '');
                }
                unset($campaignKey);
                unset($campaignKeyName);
            }
        }
        if(!empty($spendTotal)){
            foreach ($spendTotal as $k=>$v) {
                //添加入库
                $advertisingData = [
                    'stat_time_day' => $time,
                    'spend' => $v['spend'],
                    'conversion' => $v['conversion'],
                    'total_onsite_shopping_value' => $v['total_onsite_shopping_value'],
                    'onsite_shopping_roas' => $v['onsite_shopping_roas'],
                    'name' => $v['name'],
                ];
                //只能改API的数据
                $existingReport = Db::name('advertising_editingvideo')
                    ->where('stat_time_day', $time)
                    ->where('name', $v['name'])
                    ->find();
                if (empty($existingReport)) {
                    Db::name('advertising_editingvideo')->insert($advertisingData);
                } else {
                    Db::name('advertising_editingvideo')
                        ->where('stat_time_day', $time)
                        ->where('name', $v['name'])
                        ->update($advertisingData);
                }
            }
        }
        return true;
    }

    /**
    * @param array params
    * 以广告系列维度-按月份查询
    */
    public function integratedCampaign_get_month($v,$date_start,$page)
    {
        $page = $page ?? 1;
        //更新之前的
        $date_end = $v['updatetime_automatic'];

        $date_start = "2024-03-01";
        $date_end = "2024-03-31";
        $advertiser_id = $v['advertiser_id'];
        $dimensions = ['ad_id', 'stat_time_day'];
        $dimensions = json_encode($dimensions, true);
        $metrics = [
            "campaign_id",
            "campaign_name",
            "spend",
            "ad_name",
            "onsite_shopping_roas",
            "total_onsite_shopping_value",
            "conversion"
        ];
        
        $filtering[0]["field_name"] = "ad_status";
        $filtering[0]["filter_type"] = "IN";
        $filterValue = ["STATUS_ALL"];
        $encodedFilterValue = json_encode($filterValue); 
        $filtering[0]["filter_value"] = $encodedFilterValue;
        $filtering = json_encode($filtering, true);
        
        $metrics = json_encode($metrics, true);
        $url = "https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?advertiser_id=".$advertiser_id."&page=".$page."&data_level=AUCTION_AD&report_type=BASIC&dimensions=".$dimensions."&metrics=".$metrics."&filtering=".$filtering."&page_size=400&start_date=".$date_start."&end_date=".$date_end;
        $return = HttpUtil::ApiAdvaccountsGetUrl($url, $this->access_token);
        $return = json_decode($return, true);
        // dump($return);die;
        $items = [];
        $spend = 0;
        if (isset($return['data']['list']) && !empty($return['data']['list'])) {
            foreach ($return['data']['list'] as $item) {    
                $item['advertiser_id'] = $advertiser_id;
                $item = $this->tiktok_campaign_list($item);
                // if($item['spend'] > 0.001){
                //     $items[] = $item;  
                //     $spend += $item['spend'];  
                // }
        
                //队列
                // MqTaskPushLogic::mq_task_push(
                //     '',
                //     MqQueueName::QUEUE_TIKTOK_CAMPAIGN_LIST_QUEUE,
                //     $item,
                //     false
                // );
            }
            // dump($items);die;
            // if(!empty($items)){
            //     Db::name('advertising_campaign')
            //         ->where('stat_time',">=", strtotime($date_start))
            //         ->where('stat_time',"<=", strtotime($date_end))
            //         ->where('advertiser_id', $advertiser_id)
            //         ->delete();
            //     Db::name('advertising_campaign')->insertAll($items);
            // }
        }
        
        $returns['page'] = 0;
        $returns['total_page'] = 0;
        $returns['total_number'] = 0;
        if (isset($return['data']['page_info']) && !empty($return['data']['page_info'])) {
            $returns['page'] = $return['data']['page_info']['page'];
            $returns['total_page'] = $return['data']['page_info']['total_page'];
            $returns['total_number'] = $return['data']['page_info']['total_number'];
        }
        return $returns;
    }
}
